package com.atom.common.activiti.diagram;

import java.util.List;

import javax.annotation.Resource;

import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Component;

import com.atom.common.TaskStatus;
import com.atom.common.VariablesConstant;
import com.atom.common.dao.HistoricTaskDao;
import com.atom.common.entity.HistoricTaskDO;
import com.atom.common.entity.bo.SubDiagram;
import com.atom.common.entity.bo.TaskDiagramBO;
import com.atom.common.util.CommonUserResolver;
@Component
public class UserTaskDiagramHandler {
  
  @Resource
  private HistoricTaskDao historicTaskDao;
  @Resource
  private CommonUserResolver commonUserResolver;
  @Resource
  private TaskService taskService;
  
  public TaskDiagramBO getUserTaskDiagram (String taskDefinitionKey, String mainProcessInstanceId) {
    TaskDiagramBO diagram = new TaskDiagramBO(taskDefinitionKey);
    // 查询待办
    List<Task> runningTasks = taskService.createTaskQuery()
        .taskDefinitionKey(taskDefinitionKey)
        .processVariableValueEquals(VariablesConstant.MAIN_PROCESS_INSTANCE_ID, mainProcessInstanceId)
        .list();
    // 查询已办
    List<HistoricTaskDO> historicTasks = historicTaskDao.findByMainProcessInstanceIdByDefinitionKey(mainProcessInstanceId, taskDefinitionKey);
    // 设置任务状态
    diagram.setState(getTaskStatus(runningTasks, historicTasks));
    // 设置data
    for (Task runningTask : runningTasks) {
      SubDiagram sub = new SubDiagram();
      if (runningTask.getAssignee() != null) {
        sub.setAssignee(commonUserResolver.getUserNameByUserId(runningTask.getAssignee()));
      }
      sub.setStatus(TaskStatus.DOING);
      diagram.setDatas(sub);
    }
    for (HistoricTaskDO historicTask : historicTasks) {
      SubDiagram sub = new SubDiagram();
      sub.setAssignee(commonUserResolver.getUserNameByUserId(historicTask.getAssignee()));
      sub.setFinishTime(historicTask.getFinishTime());
      sub.setStatus(TaskStatus.FINISHED);
      diagram.setDatas(sub);
    }
    return diagram;
  }

  private int getTaskStatus(List<Task> runningTasks, List<HistoricTaskDO> historicTasks) {
    if (!runningTasks.isEmpty()) {
      return TaskStatus.DOING;
    }
    if (!historicTasks.isEmpty()) {
      return TaskStatus.FINISHED;
    }
    return TaskStatus.UNFINISHED;
  }

}
